package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.serivce.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;


public class SystemLogUtil {
    @Autowired
    private ISystemLogService systemLogService;
    //写入日志的方法
    public void writeLog(JoinPoint joinPoint){
        //防止死循环(系统service记录日志也会被自己aop增强)
        if (joinPoint.getTarget() instanceof ISystemLogService) {
            return;
        }

        SystemLog log = new SystemLog();
        //操作时间
        Date date = new Date();
        log.setOpTime(date);
        //当前用户
        Employee currentuser = UserContext.getCurrentuser();
        log.setOpUser(currentuser);
        //操作ip
        String remoteAddr = UserContext.getRequest().getRemoteAddr();
        log.setOpIp(remoteAddr);
        //类名
        String className = joinPoint.getTarget().getClass().getName();
        //方法名
        String methodName = joinPoint.getSignature().getName();
        //拼接全限定名
        //操作的方法
        log.setFunction(className+methodName);
        //传入的参数
        try {
            log.setParams(new ObjectMapper().writeValueAsString(joinPoint.getArgs()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //保存到数据库
        systemLogService.saveOrUpdate(log);
    }
}
